package com.example.springboot.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springboot.common.Constants;
import com.example.springboot.entity.User;
import com.example.springboot.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class TokenUtils {

    private static IUserService staticUserService;
    private static RedisUtil staticredisUtil;

    @Resource
    private IUserService userService;
    @Autowired
    private RedisUtil redisUtils;
    @PostConstruct
    public void setUserAndRedis() {
        staticUserService = userService;
        staticredisUtil = redisUtils;
    }

    /**
     * 生成token
     *
     * @return
     */
    public static String genToken(String username, String sign) {
        return JWT.create().withClaim("username",username) // 将 username 保存到 token 里面,作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(), 24 * 7)) // 2小时后token过期
                .sign(Algorithm.HMAC256(sign)); // 以 email 作为 token 的密钥
    }

    /**
     * 获取当前登录的用户信息
     *
     * @return user对象
     */
    public static User getCurrentUser() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if (StrUtil.isNotBlank(token)) {
                String username = JWT.decode(token).getClaim("username").asString();
                if (staticredisUtil.hasKey(Constants.User_KEY + ":" + username)) {
                    return (User) staticredisUtil.get(Constants.User_KEY + ":" + username);
                }
                else {
                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("username",username);
                    User user = staticUserService.getOne(queryWrapper);
                    staticredisUtil.set(Constants.User_KEY + ":" + username,user,3600);
                    return user;
                }
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }

}
